package com.ycsj.goldmedalnewconcept.common.record;

import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.ycsj.common.base.BusInfo;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherAssignHomeworkActivity;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;

/**
 * 录音功能的Service
 * Created by Administrator on 2019/3/15 0015.
 */

public class RecordingService extends Service {


    private String mFileName = null;//录音名称
    private String mFilePath = null;//录音存放地址

    private MediaRecorder mRecorder = null;//录音对象

    private long mStartingTimeMillis = 0;//录音开始时间
    private long mElapsedMillis = 0;//录音时长

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startRecording();
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        if (mRecorder != null) {
            stopRecording();
        }
    }


    // 开始录音
    public void startRecording() {
        setFileNameAndPath();

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); //录音文件保存的格式，这里保存为 mp4
        mRecorder.setOutputFile(mFilePath); // 设置录音文件的保存路径
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mRecorder.setAudioChannels(1);
        // 设置录音文件的清晰度
        mRecorder.setAudioSamplingRate(44100);
        mRecorder.setAudioEncodingBitRate(192000);
        try {
            mRecorder.prepare();
            mRecorder.start();
            mStartingTimeMillis = System.currentTimeMillis();
        } catch (IOException e) {
            mStartingTimeMillis = System.currentTimeMillis();
            Log.i("test", "prepare() failed");
        }
    }

    // 设置录音文件的名字和保存路径
    public void setFileNameAndPath() {
        File f;
        do {
            mFileName = getString(R.string.default_file_name)
                    + "_" + (System.currentTimeMillis()) + ".mp4";
            mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath();
            mFilePath += "/SoundRecorder/" + mFileName;
            f = new File(mFilePath);
        } while (f.exists() && !f.isDirectory());
    }


    // 停止录音
    public void stopRecording() {
        if (mRecorder != null) {
            try {
                //下面三个参数必须加，不加的话会奔溃，在mediarecorder.stop();
                //报错为：RuntimeException:stop failed
                mRecorder.setOnErrorListener(null);
                mRecorder.setOnInfoListener(null);
                mRecorder.setPreviewDisplay(null);
                mRecorder.stop();
            } catch (Exception e) {
                mElapsedMillis = (System.currentTimeMillis() - mStartingTimeMillis);
                SPUtil.put(this, SpKeys.RECORDAUDIOTime, mElapsedMillis);
                BusInfo busInfo = new BusInfo();
                busInfo.type = TeacherAssignHomeworkActivity.RECORDOVER;
                EventBus.getDefault().post(busInfo);
            }

            mElapsedMillis = (System.currentTimeMillis() - mStartingTimeMillis);
            //Sp中保存录制的音频的文件路径和时长
            SPUtil.put(this, SpKeys.RECORDAUDIOPATH, mFilePath);
            SPUtil.put(this, SpKeys.RECORDAUDIOTime, mElapsedMillis);
            mRecorder.release();
            mRecorder = null;

            BusInfo busInfo = new BusInfo();
            busInfo.type = TeacherAssignHomeworkActivity.RECORDOVER;
            EventBus.getDefault().post(busInfo);
        }
    }
}
